package com.yzy.config;

import com.yzy.event.MqMessageHeaderProcessor;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @author yangzhenyu
 * @version 1.0
 * @date 2022/7/14 9:58
 */@Configuration
@ConditionalOnProperty(
        prefix = "spring.rabbitmq",
        value = {"username"}
)
public class BaseRabbitConfig {
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired(required = false)
    MessagePostProcessor customPostProcessor;

    public BaseRabbitConfig() {
    }

    @Bean
    public MqMessageHeaderProcessor headerProcessor() {
        return new MqMessageHeaderProcessor();
    }

    @PostConstruct
    public void registerHeaderProcessor() {
        if (this.customPostProcessor != null) {
            this.rabbitTemplate.setBeforePublishPostProcessors(new MessagePostProcessor[]{this.headerProcessor(), this.customPostProcessor});
        } else {
            this.rabbitTemplate.setBeforePublishPostProcessors(new MessagePostProcessor[]{this.headerProcessor()});
        }

    }
}